<template>
  <div class="agent-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>智能体管理</span>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            新增智能体
          </el-button>
        </div>
      </template>

      <!-- 搜索筛选区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="场景">
            <el-select 
              v-model="searchForm.scene_id" 
              placeholder="选择场景" 
              clearable
              style="width: 200px"
              @change="handleSearch"
            >
              <el-option
                v-for="scene in sceneOptions"
                :key="scene.scene_id"
                :label="scene.displayLabel"
                :value="scene.scene_id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="智能体名称">
            <el-input
              v-model="searchForm.agent_name"
              placeholder="输入智能体名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.status" 
              placeholder="选择状态" 
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option label="停用" value="0" />
              <el-option label="启用" value="1" />
              <el-option label="训练中" value="2" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="大模型">
            <el-input
              v-model="searchForm.llm_code"
              placeholder="输入大模型代码"
              clearable
              style="width: 180px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          
          <el-form-item label="创建者">
            <el-input
              v-model="searchForm.created_by"
              placeholder="输入创建者"
              clearable
              style="width: 120px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="tableData" 
        stripe 
        border
        style="width: 100%"
      >
        <el-table-column prop="agent_name" label="智能体名称" width="150" show-overflow-tooltip />
        
        <el-table-column prop="scene_id" label="所属场景" width="120">
          <template #default="{ row }">
            <span>{{ getSceneName(row.scene_id) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="llm_code" label="大模型" width="150" show-overflow-tooltip />
        <el-table-column prop="embedding_code" label="向量模型" width="150" show-overflow-tooltip />
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="created_by" label="创建者" width="100" />
        
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown @command="(command: string) => handleDropdownCommand(command, row)">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="status">状态管理</el-dropdown-item>
                  <el-dropdown-item command="clone">克隆</el-dropdown-item>
                  <el-dropdown-item command="config">配置摘要</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属场景" prop="scene_id">
              <el-select 
                v-model="formData.scene_id" 
                placeholder="选择场景"
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option
                  v-for="scene in sceneOptions"
                  :key="scene.scene_id"
                  :label="scene.displayLabel"
                  :value="scene.scene_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="智能体代码" prop="agent_code">
              <el-select 
                v-model="formData.agent_code" 
                placeholder="选择智能体类型"
                style="width: 100%"
                filterable
                :loading="modelsLoading"
              >
                <el-option
                  v-for="(className, code) in agentTypes"
                  :key="code"
                  :label="`${code} (${className})`"
                  :value="code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="智能体名称" prop="agent_name">
              <el-input v-model="formData.agent_name" placeholder="输入智能体名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="大模型" prop="llm_code">
              <el-select 
                v-model="formData.llm_code" 
                placeholder="选择大模型"
                style="width: 100%"
                filterable
                :loading="modelsLoading"
              >
                <el-option
                  v-for="code in Object.keys(llmModels)"
                  :key="code"
                  :label="code"
                  :value="code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="向量模型" prop="embedding_code">
              <el-select 
                v-model="formData.embedding_code" 
                placeholder="选择向量模型"
                style="width: 100%"
                filterable
                :loading="modelsLoading"
              >
                <el-option
                  v-for="code in Object.keys(embeddingModels)"
                  :key="code"
                  :label="code"
                  :value="code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" style="width: 100%">
                <el-option label="停用" value="0" />
                <el-option label="启用" value="1" />
                <el-option label="训练中" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="formData.version" placeholder="如: 1.0.0" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="系统提示词" prop="sys_prompt">
          <el-input
            v-model="formData.sys_prompt"
            type="textarea"
            :rows="4"
            placeholder="输入系统提示词"
          />
        </el-form-item>

        <el-form-item label="工具列表" prop="tools_list">
          <el-select
            v-model="formData.tools_list"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择工具"
            style="width: 100%"
            filterable
            :loading="toolsLoading"
          >
            <el-option
              v-for="toolset in toolsOptions"
              :key="toolset.value"
              :label="toolset.label"
              :value="toolset.category_code"
            >
              <div class="toolset-option">
                <span class="toolset-name">{{ toolset.category_name }}</span>
                <span class="toolset-code">{{ toolset.category_code }}</span>
                <span class="toolset-tools" v-if="toolset.tools_count > 0">
                  {{ toolset.enabled_tools_count }}/{{ toolset.tools_count }}个工具
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="MCP列表" prop="mcp_list">
          <el-select
            v-model="formData.mcp_list"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择MCP工具"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="mcp in mcpOptions"
              :key="mcp.value"
              :label="mcp.label"
              :value="mcp.value"
            >
              <div class="mcp-option">
                <span class="mcp-name">{{ mcp.mcp_name }}</span>
                <span class="mcp-status">{{ mcp.status_display }}</span>
                <span class="mcp-tools" v-if="mcp.tools_count > 0">
                  {{ mcp.tools_count }}个工具
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="RAG列表" prop="rag_list">
          <el-select
            v-model="formData.rag_list"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择RAG"
            style="width: 100%"
          >
            <!-- 暂时没有选项，后续可以添加 -->
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="智能体详情"
      width="800px"
    >
      <el-descriptions :column="2" border v-if="currentAgent">
        <el-descriptions-item label="智能体ID">{{ currentAgent.agent_id }}</el-descriptions-item>
        <el-descriptions-item label="智能体代码">{{ currentAgent.agent_code }}</el-descriptions-item>
        <el-descriptions-item label="智能体名称">{{ currentAgent.agent_name }}</el-descriptions-item>
        <el-descriptions-item label="所属场景">{{ getSceneName(currentAgent.scene_id) }}</el-descriptions-item>
        <el-descriptions-item label="租户ID">{{ currentAgent.tenant_id }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentAgent.status)">
            {{ getStatusLabel(currentAgent.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="版本">{{ currentAgent.version }}</el-descriptions-item>
        <el-descriptions-item label="大模型">{{ currentAgent.llm_code }}</el-descriptions-item>
        <el-descriptions-item label="向量模型">{{ currentAgent.embedding_code }}</el-descriptions-item>
        <el-descriptions-item label="创建者">{{ currentAgent.created_by }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentAgent.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="更新者">{{ currentAgent.updated_by || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ currentAgent.updated_at ? formatDateTime(currentAgent.updated_at) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="系统提示词" :span="2">
          <div class="code-block">{{ currentAgent.sys_prompt }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 状态管理对话框 -->
    <el-dialog
      v-model="statusDialogVisible"
      title="状态管理"
      width="400px"
    >
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusForm.currentStatus)">
            {{ getStatusLabel(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.newStatus" style="width: 100%">
            <el-option label="停用" value="0" />
            <el-option label="启用" value="1" />
            <el-option label="训练中" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStatusUpdate" :loading="submitting">
            更新状态
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 克隆对话框 -->
    <el-dialog
      v-model="cloneDialogVisible"
      title="克隆智能体"
      width="400px"
    >
      <el-form :model="cloneForm" label-width="100px">
        <el-form-item label="原智能体">
          <span>{{ cloneForm.originalName }}</span>
        </el-form-item>
        <el-form-item label="新名称" required>
          <el-input v-model="cloneForm.newName" placeholder="输入新的智能体名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cloneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClone" :loading="submitting">
            克隆
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 配置摘要对话框 -->
    <el-dialog
      v-model="configDialogVisible"
      title="配置摘要"
      width="500px"
    >
      <el-descriptions :column="1" border v-if="configSummary">
        <el-descriptions-item label="智能体名称">{{ configSummary.agent_name }}</el-descriptions-item>
        <el-descriptions-item label="大模型">{{ configSummary.llm_code }}</el-descriptions-item>
        <el-descriptions-item label="向量模型">{{ configSummary.embedding_code }}</el-descriptions-item>
        <el-descriptions-item label="工具数量">{{ configSummary.tools_count }}</el-descriptions-item>
        <el-descriptions-item label="MCP数量">{{ configSummary.mcp_count }}</el-descriptions-item>
        <el-descriptions-item label="RAG数量">{{ configSummary.rag_count }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(configSummary.status)">
            {{ getStatusLabel(configSummary.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="版本">{{ configSummary.version }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus, Search, Refresh, View, Edit, ArrowDown } from '@element-plus/icons-vue'
import { agentApi } from '@/api/agent'
import { sceneApi } from '@/api/scene'
import { baseApi, type ToolOption } from '@/api/base'
import type { 
  AIWebAgent, 
  CreateAgentRequest, 
  UpdateAgentRequest,
  AgentFormData,
  AgentConfigSummary,
  AgentStatus
} from '@/types/agent'
import { AgentStatusLabels } from '@/types/agent'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const modelsLoading = ref(false)
const toolsLoading = ref(false)
const tableData = ref<AIWebAgent[]>([])
const sceneOptions = ref<any[]>([])

// 模型列表数据
const llmModels = ref<Record<string, any>>({})
const embeddingModels = ref<Record<string, any>>({})
const agentTypes = ref<Record<string, string>>({})

// 工具选项数据
const toolsOptions = ref<ToolOption[]>([])
const mcpOptions = ref<any[]>([])

// 搜索表单
const searchForm = reactive({
  scene_id: '',
  agent_name: '',
  status: '' as AgentStatus | '',
  llm_code: '',
  created_by: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const statusDialogVisible = ref(false)
const cloneDialogVisible = ref(false)
const configDialogVisible = ref(false)

const isEdit = ref(false)
const currentAgent = ref<AIWebAgent | null>(null)
const configSummary = ref<AgentConfigSummary | null>(null)

// 表单数据
const formRef = ref<FormInstance>()
const formData = reactive<AgentFormData>({
  scene_id: '',
  agent_name: '',
  agent_code: '',
  sys_prompt: '',
  llm_code: '',
  embedding_code: '',
  status: '0' as AgentStatus,
  version: '1.0.0',
  tenant_id: 'default',
  tools_list: [],
  mcp_list: [],
  rag_list: []
})

// 状态管理表单
const statusForm = reactive({
  agentId: '',
  currentStatus: '',
  newStatus: ''
})

// 克隆表单
const cloneForm = reactive({
  agentId: '',
  originalName: '',
  newName: ''
})

// 表单验证规则
const formRules = {
  scene_id: [{ required: true, message: '请选择所属场景', trigger: 'change' }],
  agent_name: [{ required: true, message: '请输入智能体名称', trigger: 'blur' }],
  agent_code: [{ required: true, message: '请输入智能体代码', trigger: 'blur' }],
  sys_prompt: [{ required: true, message: '请输入系统提示词', trigger: 'blur' }],
  llm_code: [{ required: true, message: '请选择大模型', trigger: 'change' }],
  embedding_code: [{ required: true, message: '请选择向量模型', trigger: 'change' }],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' },
    { pattern: /^[0-9]+(\.[0-9]+)*$/, message: '版本号格式不正确', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑智能体' : '新增智能体')

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      scene_id: searchForm.scene_id || undefined,
      agent_name: searchForm.agent_name || undefined,
      status: searchForm.status || undefined,
      llm_code: searchForm.llm_code || undefined,
      created_by: searchForm.created_by || undefined,
      is_deleted: 0
    }
    
    const response = await agentApi.getAgents(params)
    tableData.value = response.items
    pagination.total = response.total
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadSceneOptions = async () => {
  try {
    const response = await sceneApi.getSceneOptions()
    sceneOptions.value = response.map((scene: any) => ({
      ...scene,
      scene_id: scene.value,
      scene_name: scene.label,
      displayLabel: `${'　'.repeat(scene.level)}${scene.label}${scene.level > 0 ? ` (L${scene.level})` : ''}`
    }))
  } catch (error) {
    console.error('加载场景选项失败:', error)
  }
}

const loadModelOptions = async () => {
  modelsLoading.value = true
  try {
    // 并行加载所有数据
    const [modelsResponse, agentsResponse] = await Promise.all([
      baseApi.getAllModels(),
      baseApi.getAvailableAgents()
    ])
    
    if (modelsResponse.code === 200) {
      llmModels.value = modelsResponse.data.llm_models
      embeddingModels.value = modelsResponse.data.embedding_models
      console.log('模型列表加载成功:', {
        llm_count: modelsResponse.data.llm_count,
        embedding_count: modelsResponse.data.embedding_count
      })
    } else {
      ElMessage.warning('获取模型列表失败: ' + modelsResponse.message)
    }
    
    if (agentsResponse.code === 200) {
      agentTypes.value = agentsResponse.data.agents
      console.log('智能体类型加载成功:', {
        agent_count: agentsResponse.data.count,
        types: agentsResponse.data.agents
      })
    } else {
      ElMessage.warning('获取智能体类型失败: ' + agentsResponse.message)
    }
  } catch (error) {
    console.error('加载选项失败:', error)
    ElMessage.error('加载选项失败')
  } finally {
    modelsLoading.value = false
  }
}

const loadToolsOptions = async () => {
  toolsLoading.value = true
  try {
    const response = await baseApi.getToolsOptions()
    
    if (response.code === 200) {
      // 直接使用返回的工具集列表
      toolsOptions.value = response.data.tools
      console.log('工具集选项加载成功:', {
        toolsets_count: toolsOptions.value.length,
        toolsets: toolsOptions.value
      })
    } else {
      ElMessage.warning('获取工具集选项失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载工具集选项失败:', error)
    ElMessage.error('加载工具集选项失败')
  } finally {
    toolsLoading.value = false
  }
}

const loadMCPOptions = async () => {
  try {
    const response = await baseApi.getMCPOptions()
    
    if (response.code === 200) {
      mcpOptions.value = response.data.mcp_tools
      console.log('MCP工具选项加载成功:', {
        mcp_count: response.data.count,
        mcp_tools: response.data.mcp_tools
      })
    } else {
      ElMessage.warning('获取MCP工具选项失败: ' + response.message)
    }
  } catch (error) {
    console.error('加载MCP工具选项失败:', error)
    ElMessage.error('加载MCP工具选项失败')
  }
}

const getSceneName = (sceneId: string) => {
  const scene = sceneOptions.value.find(s => s.scene_id === sceneId)
  return scene ? scene.displayLabel : sceneId
}

const getStatusLabel = (status: string) => {
  return AgentStatusLabels[status as AgentStatus] || status
}

const getStatusType = (status: string) => {
  const colorMap: Record<string, string> = {
    '0': 'info',
    '1': 'success', 
    '2': 'warning'
  }
  return colorMap[status] || 'info'
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    scene_id: '',
    agent_name: '',
    status: '',
    llm_code: '',
    created_by: ''
  })
  handleSearch()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

const handleCreate = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: AIWebAgent) => {
  isEdit.value = true
  currentAgent.value = row
  Object.assign(formData, {
    scene_id: row.scene_id,
    agent_name: row.agent_name,
    agent_code: row.agent_code,
    sys_prompt: row.sys_prompt,
    llm_code: row.llm_code,
    embedding_code: row.embedding_code,
    status: row.status,
    version: row.version,
    tenant_id: row.tenant_id,
    tools_list: row.tools_list || [],
    mcp_list: row.mcp_list || [],
    rag_list: row.rag_list || []
  })
  dialogVisible.value = true
}

const handleView = async (row: AIWebAgent) => {
  try {
    const agent = await agentApi.getAgentById(row.agent_id)
    currentAgent.value = agent
    viewDialogVisible.value = true
  } catch (error) {
    console.error('获取智能体详情失败:', error)
    ElMessage.error('获取智能体详情失败')
  }
}

const handleDropdownCommand = (command: string, row: AIWebAgent) => {
  switch (command) {
    case 'status':
      handleStatusManagement(row)
      break
    case 'clone':
      handleCloneDialog(row)
      break
    case 'config':
      handleConfigSummary(row)
      break
    case 'delete':
      handleDelete(row)
      break
  }
}

const handleStatusManagement = (row: AIWebAgent) => {
  statusForm.agentId = row.agent_id
  statusForm.currentStatus = row.status
  statusForm.newStatus = row.status
  statusDialogVisible.value = true
}

const handleCloneDialog = (row: AIWebAgent) => {
  cloneForm.agentId = row.agent_id
  cloneForm.originalName = row.agent_name
  cloneForm.newName = ''
  cloneDialogVisible.value = true
}

const handleConfigSummary = async (row: AIWebAgent) => {
  try {
    const summary = await agentApi.getAgentConfig(row.agent_id)
    configSummary.value = summary
    configDialogVisible.value = true
  } catch (error) {
    console.error('获取配置摘要失败:', error)
    ElMessage.error('获取配置摘要失败')
  }
}

const handleDelete = async (row: AIWebAgent) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除智能体 "${row.agent_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await agentApi.deleteAgent(row.agent_id, 'admin') // TODO: 获取当前用户
    ElMessage.success('删除成功')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value && currentAgent.value) {
      const updateData: UpdateAgentRequest = {
        ...formData,
        updated_by: 'admin' // TODO: 获取当前用户
      }
      await agentApi.updateAgent(currentAgent.value.agent_id, updateData)
      ElMessage.success('更新成功')
    } else {
      const createData: CreateAgentRequest = {
        ...formData,
        tools_list: formData.tools_list,
        mcp_list: formData.mcp_list,
        rag_list: formData.rag_list,
        created_by: 'admin' // TODO: 获取当前用户
      }
      await agentApi.createAgent(createData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

const handleStatusUpdate = async () => {
  if (statusForm.currentStatus === statusForm.newStatus) {
    ElMessage.warning('状态未发生变化')
    return
  }
  
  try {
    submitting.value = true
    await agentApi.updateAgentStatus(statusForm.agentId, {
      status: statusForm.newStatus as AgentStatus,
      updated_by: 'admin' // TODO: 获取当前用户
    })
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  } finally {
    submitting.value = false
  }
}

const handleClone = async () => {
  if (!cloneForm.newName.trim()) {
    ElMessage.warning('请输入新的智能体名称')
    return
  }
  
  try {
    submitting.value = true
    await agentApi.cloneAgent(cloneForm.agentId, cloneForm.newName, 'admin') // TODO: 获取当前用户
    ElMessage.success('克隆成功')
    cloneDialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('克隆失败:', error)
    ElMessage.error('克隆失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    scene_id: '',
    agent_name: '',
    agent_code: '',
    sys_prompt: '',
    llm_code: '',
    embedding_code: '',
    status: '0' as AgentStatus,
    version: '1.0.0',
    tenant_id: 'default',
    tools_list: [],
    mcp_list: [],
    rag_list: []
  })
  formRef.value?.clearValidate()
}

// 生命周期
onMounted(() => {
  loadSceneOptions()
  loadModelOptions()
  loadToolsOptions()
  loadMCPOptions()
  loadData()
})
</script>

<style scoped>
.agent-management {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.code-block {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.toolset-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.toolset-name {
  font-weight: 500;
  color: #303133;
}

.toolset-code {
  font-size: 12px;
  color: #909399;
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  margin-left: 8px;
}

.toolset-tools {
  font-size: 11px;
  color: #67c23a;
  margin-left: auto;
}

.mcp-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.mcp-name {
  font-weight: 500;
  color: #303133;
}

.mcp-status {
  font-size: 12px;
  color: #909399;
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 3px;
  margin-left: 8px;
}

.mcp-tools {
  font-size: 11px;
  color: #67c23a;
  margin-left: auto;
}
</style> 